package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IAlertDataService;
import com.zzyl.system.mapper.SysUserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.AlertRuleMapper;
import com.zzyl.nursing.domain.AlertRule;
import com.zzyl.nursing.service.IAlertRuleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 报警规则Service业务层处理
 *
 * @author gyf
 * @date 2025-01-15
 */
@Service
public class AlertRuleServiceImpl extends ServiceImpl<AlertRuleMapper, AlertRule> implements IAlertRuleService {
    @Autowired
    private AlertRuleMapper alertRuleMapper;

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private IAlertDataService alertDataService;

    /**
     * 查询报警规则
     *
     * @param id 报警规则主键
     * @return 报警规则
     */
    @Override
    public AlertRule selectAlertRuleById(Long id) {
        return alertRuleMapper.selectById(id);
    }

    /**
     * 查询报警规则列表
     *
     * @param alertRule 报警规则
     * @return 报警规则
     */
    @Override
    public List<AlertRule> selectAlertRuleList(AlertRule alertRule) {
        return alertRuleMapper.selectAlertRuleList(alertRule);
    }

    /**
     * 新增报警规则
     *
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int insertAlertRule(AlertRule alertRule) {
        return alertRuleMapper.insert(alertRule);
    }

    /**
     * 修改报警规则
     *
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int updateAlertRule(AlertRule alertRule) {
        return alertRuleMapper.updateById(alertRule);
    }

    /**
     * 批量删除报警规则
     *
     * @param ids 需要删除的报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleByIds(Long[] ids) {
        return alertRuleMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除报警规则信息
     *
     * @param id 报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleById(Long id) {
        return alertRuleMapper.deleteById(id);
    }

    /**
     * 报警规则过滤
     */
    @Override
    public void alertFilter() {
        //查询有没有启用的规则
        List<AlertRule> rules = list(Wrappers.<AlertRule>lambdaQuery().eq(AlertRule::getStatus, 1));
        //判断是否为空,为空则返回
        if (ObjectUtil.isEmpty(rules)) {
            return;
        }
        //不为空则,查询所有设备的最新物模型数据
        List<Object> deviceDataLists = redisTemplate.opsForHash().values(CacheConstants.IOT_DEVICE_DATA_LAST);
        //判断物模型数据是否为空为空则返回
        if (ObjectUtil.isEmpty(deviceDataLists)) {
            return;
        }
        //遍历获取到的物模型集合的集合
        deviceDataLists.forEach(list -> {
            //解析为物模型集合
            List<DeviceData> deviceDataList = (List<DeviceData>) list;
            deviceDataList.forEach(deviceData -> {
                //遍历每一个物模型数据,交给数据报警处理器
                alertHander(deviceData);

            });
        });

    }

    /**
     * 报警规则处理器
     *
     * @param deviceData
     */
    private void alertHander(DeviceData deviceData) {


        //查询物模型对应的规则列表
        List<AlertRule> rules = list(Wrappers.<AlertRule>lambdaQuery()
                .eq(AlertRule::getProductKey, deviceData.getProductKey())
                .eq(AlertRule::getFunctionId, deviceData.getFunctionId())
                .in(AlertRule::getIotId, -1, deviceData.getIotId())
                .eq(AlertRule::getStatus, 1));
        //判断规则列表是否为空,为空则返回
        if (ObjectUtil.isEmpty(rules)) {
            return;
        }
        //不为空,遍历每一条规则
        rules.forEach(rule -> {
            //预报警次数的key
            String alert_trigger_count = "iot_alert:" + "alert_trigger_count" + rule.getProductKey() + rule.getIotId() + rule.getFunctionId() + rule.getId();
            //沉默周期的key
            String alert_silent = "iot_alert:" + "alert_silent" + rule.getProductKey() + rule.getIotId() + rule.getFunctionId() + rule.getId();

            //判断物模型上报时间是否在规则的生效时间内
            String[] times = rule.getAlertEffectivePeriod().split("~");
            LocalTime begin = LocalTime.parse(times[0]);
            LocalTime end = LocalTime.parse(times[1]);
            LocalTime alarmTime = deviceData.getAlarmTime().toLocalTime();
            //如果不在,则返回
            if (alarmTime.isBefore(begin) || alarmTime.isAfter(end)) {
                return;
            }
            //检验数据是否达到阈值
            Double dataValue = Double.valueOf(deviceData.getDataValue());
            String operator = rule.getOperator();
            Double value = rule.getValue();
            int compare = Double.compare(dataValue, value);
            //如果没达到,清空预报警次数,返回
            if ("<".equals(operator) && compare >= 0 || ">=".equals(operator) && compare == -1) {
                redisTemplate.delete(alert_trigger_count);
                return;
            }
            //查询沉默周期,如果存在,则返回
            Object o = redisTemplate.opsForValue().get(alert_silent);
            if (ObjectUtil.isNotEmpty(o)) {
                return;
            }
            //查询已报警的次数,如果没有则添加预报警次数值为1,如果有则加1,在与规则的预报警次数比较
            Integer num = (Integer) redisTemplate.opsForValue().get(alert_trigger_count);
            Integer duration = rule.getDuration();
            if (ObjectUtil.isEmpty(num)) {
                num = 1;
//                redisTemplate.opsForValue().set(alert_trigger_count,1);
//                return;
            } else {
                num = num + 1;
            }

            if (duration.equals(num)) {
                redisTemplate.delete(alert_trigger_count);
            } else {
                redisTemplate.opsForValue().set(alert_trigger_count, num);
                return;
            }
            //添加沉默周期
            Integer alertSilentPeriod = rule.getAlertSilentPeriod();
            redisTemplate.opsForValue().set(alert_silent, -1, alertSilentPeriod, TimeUnit.MINUTES);

            //新增报警记录
            batchInsertAlertRecord(deviceData, rule);
        });

    }

    private void batchInsertAlertRecord(DeviceData deviceData, AlertRule rule) {
        List<Long> longs;
        if (rule.getAlertDataType() == 1) {
            //查询维修工id列表
            longs = sysUserRoleMapper.selectUserIdByRoleName("维修工");
        } else {
            //查询护理人员id列表
            if (deviceData.getLocationType() == 1) {
                //固定设备查询方式
                longs = deviceMapper.selectNursingIdsByIotIdWithBed(deviceData.getIotId());
            } else {
                //随身设备查询方式
                longs = deviceMapper.selectNursingIdsByIotIdWithElder(deviceData.getIotId());
            }
        }
        //查询超级管理员id列表
        List<Long> superIds = sysUserRoleMapper.selectUserIdByRoleName("超级管理员");
        //添加进longs
        longs.addAll(superIds);

        //封装报警数据到集合
        ArrayList<AlertData> alertDatas = new ArrayList<>();
        longs.forEach(id -> {
            AlertData alertData = BeanUtil.toBean(deviceData, AlertData.class);

            //因为物模型数据有id,copy了多余的id,所以置空
            alertData.setId(null);
            alertData.setUserId(id);
            alertData.setAlertRuleId(rule.getId());
            alertData.setAlertReason(rule.getFunctionName() + rule.getOperator() + rule.getValue() + "持续了" + rule.getDuration() + "分钟");
            alertData.setType(rule.getAlertDataType());
            alertData.setStatus(0);

            alertDatas.add(alertData);
        });

        //批量添加
        alertDataService.saveBatch(alertDatas);
    }
}
